<?php

namespace app\common\controller;

use fast\Http;
use addons\epay\library\Service;
use think\Cache;
use Yansongda\Pay\Pay;
use think\Db;

class MyHelp
{

    /**
     * 获取token
     */
    public static function wxGeTtoken($admin_id)
    {
        if (Cache::has($admin_id . 'access_token')) {
            return Cache::get($admin_id . 'access_token');
        }
        $cfg = Db::table('fa_admin_cfg')->where('admin_id', $admin_id)->find();
        $appid = $cfg['wechat_mp_app_id'];
        $screct = $cfg['wechat_mp_app_secret'];
        $rst =  http::get('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $appid . '&secret=' . $screct . '');
        //  echo $rst;
        //  exit;
        //{"access_token":"58_M9FnoIrDUp10L0iKrSWgc3uDul5v0j8Ryop-tkEF78PMHdH3Q3mcVwOmW-qIZmdQNdj_O6T_4QXzJtv40enBiCfgokfYMS1lnyRAhK877edkLXTBWlOhj4j1V8rdj0K1NBRYqKDz23bes7k9HLFcAIACGA","expires_in":7200}
        //return  $rst;

        $rst_arr = json_decode($rst, true);
        if (isset($rst_arr['access_token'])) {
            $access_token = $rst_arr['access_token'];
            Cache::set($admin_id . 'access_token', $access_token, 300);
            return $access_token;
        } else {
            self::dingding('微信订单：token' . $cfg['admin_id'] . '获取失败：' . $rst, 'efd06b76ed725c4d3ee092080ce07ce50a1dabaa49914f0eead1299f78433b3d');
            return '';
        }
    }

    /**
     * 计算加价
     */
    public static function getPrice($admin, $cb, $mz)
    {
        // $admin = db::table('fa_admin')->where('id', $this->auth->id)->find();
        $h5_add = $admin['h5_add'];
        $h5_admin_s = $admin['h5_admin_s'];
        //平台 A B h5
        //平台 A h5
        $add = $mz / 100 * $h5_add;

        $add_admin = $mz / 100 * $h5_admin_s;

        // $ddd['add'] = $add;
        // $ddd['add_admin'] = $add_admin;



        $lr[] = [
            'id' => $admin['id'],
            'money' => $add,
            'remark' => 'h5站长利润'
        ];
        $lr[] = [
            'id' => $admin['s_id'],
            'money' => $add_admin,
            'remark' => 'A利润'
        ];
        $add_admin_2 = 0;
        if ($admin['s_id'] > 1) {
            $admin_s = db::table('fa_admin')->where('id', $admin['s_id'])->find(); //分销权限的A
            $add_admin_2 = $mz / 100 * $admin_s['h5_admin_s'];
            $lr[] = [
                'id' => $admin_s['s_id'], //正常情况下是1
                'money' => $add_admin_2,
                'remark' => '平台利润'
            ];
        }



        $ddd['price'] = round($cb + $add_admin + $add_admin_2, 2);
        $ddd['price_h5'] = round($cb + $add_admin + $add_admin_2 + $add, 2);

        $ddd['lr'] = $lr;
        return $ddd;
    }
    /**
     * 获取价格 新算法
     * price 站长成本价
     * price_h5 站长h5价
     */
    public static function getPriceNew($admin, $goodsid, $api = 0)
    {
        //先算出来成本价
        $goods_cache = cache::get('goods_cache');
        $goodsArr = [];
        if (!$goods_cache) {
            $r = db::table('fa_hf_goods')->select();
            foreach ($r as $key => $value) {
                $goodsArr[$value['id']] = $value;
            }
            cache::set('goods_cache', $goodsArr, 24 * 60 * 60);
        } else {
            $goodsArr = $goods_cache;
        }
        // echo json_encode($goodsArr);
        // exit;
        // return $goodsArr;
        $pt_add  = $goodsArr[$goodsid]['mz'] / 100 * 1;

        $cb = round($goodsArr[$goodsid]['cb'] + $pt_add, 2); //平台加完价的 站长成本价
        $ddd['price'] = $cb;
        $ddd['price_h5'] = $cb;
        $lr = [];
        $goods_addprice = db::table('fa_hf_goods_addprice')->where('admin_id', $admin['id'])->where('type', 2)->where('goodsid', $goodsid)->find();
        if ($goods_addprice) {
            $cb = round($cb + $goods_addprice['add'], 2); //上级加价


            $lr[] = [
                'id' => $admin['s_id'],
                'money' => $goods_addprice['add'],
                'remark' => 'A利润'
            ];
            $ddd['price'] = $cb;
            $ddd['price_h5'] = $cb;
        }
        if ($api == 0) { //h5才有分佣
            $goods_addprice_h5 = db::table('fa_hf_goods_addprice')->where('admin_id', $admin['id'])->where('type', 1)->where('goodsid', $goodsid)->find();
            if ($goods_addprice_h5) {
                $h5_add = $goods_addprice_h5['add'];
                $lr[] = [
                    'id' => $admin['id'],
                    'money' => $h5_add,
                    'remark' => 'h5站长利润'
                ];
                $ddd['price_h5'] = round($cb + $h5_add, 2);
            }
        }



        $ddd['lr'] = $lr;
        return $ddd;
    }
    /**
     * 下单成功模板消息
     */
    public static function sendtemplateSucc($admin_id, $dataparam = [])
    {
        $ACCESS_TOKEN = self::wxGeTtoken($admin_id);
        $template_id = self::getTemplate($admin_id, 'OPENTM415557602', 'order_tp');
        // $dataparam = [
        //     'touser' => 'o-qMS6ZTli87QzPgRWvIWUWzPjyg',
        //     'orderno' => time(),
        //     'account' => '123456',
        //     'price' => '94',
        // ];
        $data = [
            'touser' => $dataparam['touser'],
            'access_token' => $ACCESS_TOKEN,
            'template_id' => $template_id,
            'client_msg_id' => $dataparam['orderno'] . 'order',

            'data' => [
                'first' => [
                    'value' => '充值账号：' . $dataparam['account'] . '，订单已经提交，正在充值中.....'
                ],
                'keyword1' => [
                    'value' => $dataparam['orderno']
                ],
                'keyword2' => [
                    'value' =>  $dataparam['price']
                ],
                'remark' => [
                    'value' => '如有任何疑问请联系在线客服',
                    "color" => "#FF0000"
                ],

            ]
        ];

        $rst =   Http::post('https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=' . $ACCESS_TOKEN, json_encode($data));
        //return   $rst;
        //{"errcode":0,"errmsg":"ok","msgid":2490909481980362755}
        $rst_arr = json_decode($rst, true);
        if (isset($rst_arr['errmsg'])) {
            if ($rst_arr['errmsg'] != "ok") {
                self::dingding('微信订单：订单号' . $dataparam['orderno'] . '推送失败：' . $rst, 'efd06b76ed725c4d3ee092080ce07ce50a1dabaa49914f0eead1299f78433b3d');
            }
        } else {
            self::dingding('微信订单：订单号' . $dataparam['orderno'] . '推送失败：' . $rst, 'efd06b76ed725c4d3ee092080ce07ce50a1dabaa49914f0eead1299f78433b3d');
        }
        //return  $template_id;
    }
    /**
     * 订单充值成功模板消息
     */
    public static function sendtemplateSuccOrder($admin_id, $dataparam = [])
    {
        $ACCESS_TOKEN = self::wxGeTtoken($admin_id);
        // return $ACCESS_TOKEN;
        $template_id = self::getTemplate($admin_id, 'OPENTM417049252', 'succ_tp');

        //失败OPENTM411628258
        // $dataparam = [
        //     'touser' => 'o-qMS6ZTli87QzPgRWvIWUWzPjyg',
        //     'orderno' => time(),
        //     'account' => '123456',
        //     'price' => '94',
        //     'title' => '国网100元充值',
        //     'type' => '电费'
        // ];
        $data = [
            'touser' => $dataparam['touser'],
            'access_token' => $ACCESS_TOKEN,
            'template_id' => $template_id,
            'client_msg_id' => $dataparam['orderno'] . 'succ',

            'data' => [
                'first' => [
                    'value' => '充值账号：' . $dataparam['account'] . '，已经充值成功'
                ],
                'keyword1' => [
                    'value' => $dataparam['type']
                ],
                'keyword2' => [
                    'value' => $dataparam['title']
                ],
                'keyword3' => [
                    'value' => self::Get_Date()
                ],
                'remark' => [
                    'value' => '如有任何疑问请联系在线客服',
                    "color" => "#FF0000"
                ],

            ]
        ];

        $rst =   Http::post('https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=' . $ACCESS_TOKEN, json_encode($data));
        //return   $rst;
        //{"errcode":0,"errmsg":"ok","msgid":2490909481980362755}
        $rst_arr = json_decode($rst, true);
        if (isset($rst_arr['errmsg'])) {
            if ($rst_arr['errmsg'] != "ok") {
                self::dingding('微信订单：订单号' . $dataparam['orderno'] . '推送失败：' . $rst, 'efd06b76ed725c4d3ee092080ce07ce50a1dabaa49914f0eead1299f78433b3d');
            }
        } else {
            self::dingding('微信订单：订单号' . $dataparam['orderno'] . '推送失败：' . $rst, 'efd06b76ed725c4d3ee092080ce07ce50a1dabaa49914f0eead1299f78433b3d');
        }
    }
    /**
     * 订单充值失败模板消息
     */
    public static function sendtemplateErrorOrder($admin_id, $dataparam = [])
    {
        $ACCESS_TOKEN = self::wxGeTtoken($admin_id);

        $template_id = self::getTemplate($admin_id, 'OPENTM410226011', 'error_tp');
        //return $template_id;
        //失败OPENTM411628258
        // $dataparam = [
        //     'touser' => 'o-qMS6ZTli87QzPgRWvIWUWzPjyg',
        //     'orderno' => time(),
        //     'account' => '123456',
        //     'price' => '94',
        //     'title' => '国网100元充值',
        //     'type' => '电费'
        // ];
        $data = [
            'touser' => $dataparam['touser'],
            'access_token' => $ACCESS_TOKEN,
            'template_id' => $template_id,
            'client_msg_id' => $dataparam['orderno'] . 'error',

            'data' => [
                'first' => [
                    'value' => '你下单的商品充值失败'
                ],
                'keyword1' => [
                    'value' => $dataparam['account']
                ],
                'keyword2' => [
                    'value' => $dataparam['title']
                ],
                'keyword3' => [
                    'value' => $dataparam['price']
                ],
                'keyword4' => [
                    'value' => self::Get_Date()
                ],
                'remark' => [
                    'value' => '如有任何疑问请联系在线客服',
                    "color" => "#FF0000"
                ],

            ]
        ];

        $rst =   Http::post('https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=' . $ACCESS_TOKEN, json_encode($data));
        //  return   $rst;
        //{"errcode":0,"errmsg":"ok","msgid":2490909481980362755}
        $rst_arr = json_decode($rst, true);
        // $rst_arr = json_decode($rst, true);
        if (isset($rst_arr['errmsg'])) {
            if ($rst_arr['errmsg'] != "ok") {
                self::dingding('微信订单：订单号' . $dataparam['orderno'] . '推送失败：' . $rst, 'efd06b76ed725c4d3ee092080ce07ce50a1dabaa49914f0eead1299f78433b3d');
            }
        } else {
            self::dingding('微信订单：订单号' . $dataparam['orderno'] . '推送失败：' . $rst, 'efd06b76ed725c4d3ee092080ce07ce50a1dabaa49914f0eead1299f78433b3d');
        }
        return $rst;
    }
    /**
     * 获取模板id
     */
    public static function getTemplate($admin_id, $template_id_short = "OPENTM415557602", $type = 'succ_tp')
    {
        $cfg = db::table('fa_admin_cfg')->where('admin_id', $admin_id)->find();
        if ($cfg['succ_tp'] && $type == "succ_tp") {
            return $cfg['succ_tp'];
        } elseif ($cfg['order_tp'] && $type == "order_tp") {
            return $cfg['order_tp'];
        } elseif ($cfg['error_tp'] && $type == "error_tp") {
            return $cfg['error_tp'];
        }
        $ACCESS_TOKEN = self::wxGeTtoken($admin_id);
        $data = [
            'access_token' => $ACCESS_TOKEN,
            'template_id_short' => $template_id_short
        ];

        $rst =   Http::post('https://api.weixin.qq.com/cgi-bin/template/api_add_template?access_token=' . $ACCESS_TOKEN, json_encode($data));
        // echo   $rst;
        $rst_arr = json_decode($rst, true);
        if (isset($rst_arr['template_id'])) {
            $template_id = $rst_arr['template_id'];
            db::table('fa_admin_cfg')->where('admin_id', $admin_id)->update([$type => $template_id]);
        } else {
            self::dingding('微信订单：站长' . $admin_id . '模板：' . $rst, 'efd06b76ed725c4d3ee092080ce07ce50a1dabaa49914f0eead1299f78433b3d');
            $template_id = "";
        }
        return  $template_id;
        //{"errcode":0,"errmsg":"ok","template_id":"R5WO_m2pxS8QcFU7iZVeE-ytP6vLlJxT1fmp9Y4Q4W8"}
    }
    /*
    * 将时间戳转换为北京标准时间，如果时间戳为空则是取当前时间
    * 2020-03-24 19:35:16
    */
    public static function Get_Date($time = '')
    {
        if (empty($time)) {
            $time = time();
        }
        if (!is_numeric($time)) {
            return $time;
        }
        return date('Y-m-d H:i:s', $time);
    }
    /**
     * 退款
     */
    public static function refund($params = [])
    {
        // $params = [
        //     'admin_id' => '66',
        //     'order' => '20220712040259000000192483',
        //     'type' => 'alipay',
        //     'amount' => '100', //乘以100单位分
        //     'total' => '9400',
        // ];
        $cfg = db::table('fa_admin_cfg')->where('admin_id', $params['admin_id'])->find();
        if ($params['type'] == 'wechat') {
            $config = Service::getConfig('wechat');
            $config['app_id']  = $cfg['wechat_mp_app_id'];
            $config['appid']  = $cfg['wechat_mp_app_id'];
            $config['app_secret']  = $cfg['wechat_mp_app_secret'];
            $config['mch_id']  = $cfg['wechat_mch_id'];
            $config['key']  = $cfg['wechat_key'];
            $cert_client = ROOT_PATH . str_replace('/', DS, substr('\addons/epay/certs/apiclient_cert_' . $params['admin_id'] . '.pem', 1));
            //$config['cert_client']  = str_replace('\\', '\/', $cert_client);
            $config['cert_client']  = $cert_client;
            $cert_key = ROOT_PATH . str_replace('/', DS, substr('\addons/epay/certs/apiclient_key_' . $params['admin_id'] . '.pem', 1));
            //$config['cert_key']  = str_replace('\\', '\/', $cert_key);
            $config['cert_key']  = $cert_key;
            //  {"return_code":"SUCCESS","return_msg":"OK","appid":"wx98ebcf474e5e768b","mch_id":"1562257591","nonce_str":"FfiHvW1ktvt53hYg","sign":"6A5F530DA8160E7E1F6B8DC61380992F","result_code":"SUCCESS","transaction_id":"4200001490202207127198282660","out_trade_no":"20220712124354000000121049","out_refund_no":"1657595098","refund_id":"50302002342022071222606684654","refund_channel":[],"refund_fee":"200","coupon_refund_fee":"0","total_fee":"9400","cash_fee":"9400","coupon_refund_count":"0","cash_refund_fee":"200"}
            $order = [
                'out_trade_no' => $params['order'],
                'out_refund_no' => time(),
                'total_fee' => $params['total'],
                'refund_fee' => $params['amount'],
                'refund_desc' => '订单退款',
            ];
            $wechat = Pay::wechat($config);
            $result = $wechat->refund($order);
        } else {
            $config = Service::getConfig('alipay');
            $config['app_id']  = $cfg['alipay_app_id'];
            $config['private_key']  = $cfg['alipay_private_key'];
            $ali_public_key = ROOT_PATH . str_replace('/', DS, substr('\addons/epay/certs/alipayCertPublicKey_' . $params['admin_id'] . '.crt', 1));
            //$config['ali_public_key']  = str_replace('\\', '\/', $ali_public_key);
            $config['ali_public_key']  = $ali_public_key;
            $app_cert_public_key = ROOT_PATH . str_replace('/', DS, substr('\addons/epay/certs/appCertPublicKey_' . $params['admin_id'] . '.crt', 1));
            // $config['app_cert_public_key']  = str_replace('\\', '\/', $app_cert_public_key);
            $config['app_cert_public_key'] = $app_cert_public_key;
            $alipay_root_cert = ROOT_PATH . str_replace('/', DS, substr('\addons/epay/certs/alipayRootCert_' . $params['admin_id'] . '.crt', 1));
            //$config['alipay_root_cert']  = str_replace('\\', '\/', $alipay_root_cert);
            $config['alipay_root_cert']  = $alipay_root_cert;
            $order = [
                'out_trade_no' => $params['order'],
                'refund_amount' => $params['amount'],
                'out_request_no' => $params['order']
            ];
            $wechat = Pay::alipay($config);
            $result = $wechat->refund($order);
        }



        return  $result;
    }
    /**
     * 退款
     */
    public static function refundkq($params = [])
    {
        // $params = [
        //     'admin_id' => '66',
        //     'order' => '20220712040259000000192483',
        //     'type' => 'alipay',
        //     'amount' => '100', //乘以100单位分
        //     'total' => '9400',
        // ];
        $cfg = db::table('fa_admin_cfg')->where('admin_id', $params['admin_id'])->find();
        if ($params['type'] == 'wechat') {
            $config = Service::getConfig('wechat');
            $config['app_id']  = $cfg['wechat_mp_app_id_kq'];
            $config['appid']  = $cfg['wechat_mp_app_id_kq'];
            $config['app_secret']  = $cfg['wechat_mp_app_secret_kq'];
            $config['mch_id']  = $cfg['wechat_mch_id_kq'];
            $config['key']  = $cfg['wechat_key_kq'];
            $cert_client = ROOT_PATH . str_replace('/', DS, substr('\addons/epay/certs/apiclient_cert_' . $params['admin_id'] . '_kq.pem', 1));
            //$config['cert_client']  = str_replace('\\', '\/', $cert_client);
            $config['cert_client']  = $cert_client;
            $cert_key = ROOT_PATH . str_replace('/', DS, substr('\addons/epay/certs/apiclient_key_' . $params['admin_id'] . '_kq.pem', 1));
            //$config['cert_key']  = str_replace('\\', '\/', $cert_key);
            $config['cert_key']  = $cert_key;
            //  {"return_code":"SUCCESS","return_msg":"OK","appid":"wx98ebcf474e5e768b","mch_id":"1562257591","nonce_str":"FfiHvW1ktvt53hYg","sign":"6A5F530DA8160E7E1F6B8DC61380992F","result_code":"SUCCESS","transaction_id":"4200001490202207127198282660","out_trade_no":"20220712124354000000121049","out_refund_no":"1657595098","refund_id":"50302002342022071222606684654","refund_channel":[],"refund_fee":"200","coupon_refund_fee":"0","total_fee":"9400","cash_fee":"9400","coupon_refund_count":"0","cash_refund_fee":"200"}
            $order = [
                'out_trade_no' => $params['order'],
                'out_refund_no' => time(),
                'total_fee' => $params['total'],
                'refund_fee' => $params['amount'],
                'refund_desc' => '订单退款',
            ];
            $wechat = Pay::wechat($config);
            $result = $wechat->refund($order);
        } else {
            $config = Service::getConfig('alipay');
            $config['app_id']  = $cfg['alipay_app_id_kq'];
            $config['private_key']  = $cfg['alipay_private_key_kq'];
            $ali_public_key = ROOT_PATH . str_replace('/', DS, substr('\addons/epay/certs/alipayCertPublicKey_' . $params['admin_id'] . '_kq.crt', 1));
            //$config['ali_public_key']  = str_replace('\\', '\/', $ali_public_key);
            $config['ali_public_key']  = $ali_public_key;
            $app_cert_public_key = ROOT_PATH . str_replace('/', DS, substr('\addons/epay/certs/appCertPublicKey_' . $params['admin_id'] . '_kq.crt', 1));
            // $config['app_cert_public_key']  = str_replace('\\', '\/', $app_cert_public_key);
            $config['app_cert_public_key'] = $app_cert_public_key;
            $alipay_root_cert = ROOT_PATH . str_replace('/', DS, substr('\addons/epay/certs/alipayRootCert_' . $params['admin_id'] . '_kq.crt', 1));
            //$config['alipay_root_cert']  = str_replace('\\', '\/', $alipay_root_cert);
            $config['alipay_root_cert']  = $alipay_root_cert;
            $order = [
                'out_trade_no' => $params['order'],
                'refund_amount' => $params['amount'],
                'out_request_no' => $params['order']
            ];
            $wechat = Pay::alipay($config);
            $result = $wechat->refund($order);
        }



        return  $result;
    }
    /**
     * 微信转账
     */
    public static function transferWx($params)
    {
        // $params = [
        //     'admin_id' => '',
        //     'order' => '',
        //     'openid' => '',
        //     'amount' => '', //乘以100单位分
        // ];
        $config = Service::getConfig('wechat');

        $cfg = db::table('fa_admin_cfg')->where('admin_id', $params['admin_id'])->find();

        $config['app_id']  = $cfg['wechat_mp_app_id'];
        $config['appid']  = $cfg['wechat_mp_app_id'];
        $config['app_secret']  = $cfg['wechat_mp_app_secret'];
        $config['mch_id']  = $cfg['wechat_mch_id'];
        $config['key']  = $cfg['wechat_key'];
        $cert_client = ROOT_PATH . str_replace('/', DS, substr('\addons/epay/certs/apiclient_cert_' . $params['admin_id'] . '.pem', 1));
        //$config['cert_client']  = str_replace('\\', '\/', $cert_client);
        $config['cert_client']  = $cert_client;
        $cert_key = ROOT_PATH . str_replace('/', DS, substr('\addons/epay/certs/apiclient_key_' . $params['admin_id'] . '.pem', 1));
        //$config['cert_key']  = str_replace('\\', '\/', $cert_key);
        $config['cert_key']  = $cert_key;
        $order = [
            'partner_trade_no' => $params['order'],              //商户订单号
            'openid' => $params['openid'],                        //收款人的openid
            'check_name' => 'NO_CHECK',            //NO_CHECK：不校验真实姓名\FORCE_CHECK：强校验真实姓名
            // 're_user_name'=>'张三',              //check_name为 FORCE_CHECK 校验实名的时候必须提交
            'amount' => $params['amount'],                       //企业付款金额，单位为分
            'desc' => '会员提现',                  //付款说明
        ];
        $wechat = Pay::wechat($config);
        $result = $wechat->transfer($order);
        // $pay = Pay::wechat($this->config)->mp($order);
        //{"appId":"wx98ebcf474e5e768b","timeStamp":"1656837286","nonceStr":"eZbgYn23UXAv2AxU","package":"prepay_id=wx0316344900702387acdd9b59f2cdcf0000","signType":"MD5","paySign":"21ADA22078DA88842A0DE6FFE561DCFA"}

        //{"return_code":"SUCCESS","return_msg":[],"mch_appid":"wx98ebcf474e5e768b","mchid":"1562257591","nonce_str":"ZgTBjCt3SGDYmlDX","result_code":"SUCCESS","partner_trade_no":"123456789","payment_no":"10101138555432207037936582540863","payment_time":"2022-07-03 22:21:18"}
        //{"return_code":"SUCCESS","return_msg":"此IP地址不允许调用接口，如有需要请登录微信支付商户平台更改配置","mch_appid":"wx98ebcf474e5e768b","mchid":"1562257591","result_code":"FAIL","err_code":"NO_AUTH","err_code_des":"此IP地址不允许调用接口，如有需要请登录微信支付商户平台更改配置"}
        return  $result;
    }
    /**
     * 支付宝转账
     */
    public static function transferAl($params)
    {
        // $params = [
        //     'admin_id' => '',
        //     'order' => '',
        //     'number' => '', //支付宝账号
        //     'name' => '',
        //     'amount' => '', //乘以100单位分
        // ];
        $config = Service::getConfig('alipay');

        $cfg = db::table('fa_admin_cfg')->where('admin_id', $params['admin_id'])->find();
        $config['app_id']  = $cfg['alipay_app_id'];
        $config['private_key']  = $cfg['alipay_private_key'];
        $ali_public_key = ROOT_PATH . str_replace('/', DS, substr('\addons/epay/certs/alipayCertPublicKey_' . $params['admin_id'] . '.crt', 1));
        //$config['ali_public_key']  = str_replace('\\', '\/', $ali_public_key);
        $config['ali_public_key']  = $ali_public_key;
        $app_cert_public_key = ROOT_PATH . str_replace('/', DS, substr('\addons/epay/certs/appCertPublicKey_' . $params['admin_id'] . '.crt', 1));
        // $config['app_cert_public_key']  = str_replace('\\', '\/', $app_cert_public_key);
        $config['app_cert_public_key'] = $app_cert_public_key;
        $alipay_root_cert = ROOT_PATH . str_replace('/', DS, substr('\addons/epay/certs/alipayRootCert_' . $params['admin_id'] . '.crt', 1));
        //$config['alipay_root_cert']  = str_replace('\\', '\/', $alipay_root_cert);
        $config['alipay_root_cert']  = $alipay_root_cert;


        // $number = '3052985@qq.com';
        // $name = '杨兵涛';
        // $money = 0.1;

        $order = [
            'out_biz_no'   => $params['order'],
            'product_code' => 'TRANS_ACCOUNT_NO_PWD',
            'biz_scene'    => 'DIRECT_TRANSFER',
            'payee_info'   => [
                'identity'      => $params['number'],
                'identity_type' => 'ALIPAY_LOGON_ID',
                'name'          => $params['name'],
            ],
            'trans_amount' => $params['amount'],
            "order_title" => "会员提现",
            // "business_params" => [
            //     "payer_show_name" => "结算中心"
            // ]
        ];
        $pay = Pay::alipay($config);


        $result = $pay->transfer($order);
        // $alipay = Pay::alipay($config);
        // $result = $alipay->transfer($order);
        //{"code":"10000","msg":"Success","order_id":"20220704020070011500850022684058","out_biz_no":"545544444445","pay_fund_order_id":"20220704020070011500850022684058","status":"SUCCESS","trans_date":"2022-07-04 23:43:26"}
        return $result;
    }

    public static function mobileGsd($mobile)
    {
        // $rst = http::get('http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=' . $mobile);
        // $rst = iconv('GB2312', 'UTF-8', $rst);
        // //{"carrier":"广东电信","province":"广东","catName":"中国电信","telString":"17708645325","mts":"1770864"}__GetZoneResult_ = { }
        // $rst = "{" . MyHelp::getSubstr($rst, '{', '}_') . "}";
        // $a = json_decode($rst, true);
        // if (isset($a['carrier'])) {
        //     $t1 = $a['carrier']; //河南移动
        //     $t2 = $a['province']; //省份 河南
        // }
        $rst = http::get('https://www.baifubao.com/callback?cmd=1059&callback=phone&phone=' . $mobile);
        ///*fgg_again*/phone({"meta":{"result":"0","result_info":"","jump_url":""},"data":{"operator":"移动","area":"江苏","area_operator":"江苏移动","support_price":{"1000":"999","10000":"9990","2000":"1998","20000":"19980","3000":"2997","30000":"29970","5000":"4995","50000":"49950"},"promotion_info":null}})
        $rst = self::getSubstr($rst, '(', ')');

        $a = json_decode($rst, true);
        if (isset($a['data']['area_operator'])) {
            $t1 = $a['data']['area_operator']; //河南移动
            $t2 = $a['data']['area']; //省份 河南
        } else {
            return false;
        }

        if (self::strexists($t1, '移动')) {
            $type = "移动";
        } elseif (self::strexists($t1, '联通')) {
            $type = "联通";
        } elseif (self::strexists($t1, '电信')) {
            $type = "电信";
        } else {
            $type = "移动";
        }
        $data['t1'] = $t1;
        $data['t2'] = $t2;
        $data['t3'] = $type;
        //echo json($data);
        // exit;
        return $data;
    }
    /**
     * 随机字符生成
     *
     * @param [type] $length
     * @param string $p all 所有 num  数字 lower 小写  upper 大写
     * @return void
     */
    public static function rand_str($length, $p = 'all')
    {
        $yznums = '0123456789';
        $lowers = 'abcdefghijklmnopqrstuvwxyz';
        $uppers = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        if ($p == 'all') {
            $src = $yznums . $lowers . $uppers;
        } else {
            $src = '';
            if (strpos($p, 'num') !== false) {
                $src .= $yznums;
            }

            if (strpos($p, 'lower') !== false) {
                $src .= $lowers;
            }

            if (strpos($p, 'upper') !== false) {
                $src .= $uppers;
            }
        }
        return $src ? substr(str_shuffle($src), 0, $length) : $src;
    }

    /**
     * 获取ip地区
     */
    public static function get_ip_city($ip)
    {
        $url = 'http://whois.pconline.com.cn/ipJson.jsp?json=true&ip=';
        $city = http::get($url . $ip);
        $city = mb_convert_encoding($city, "UTF-8", "GB2312");
        $city = json_decode($city, true);
        if ($city['city']) {
            $location = $city['pro'] . $city['city'];
        } else {
            $location = $city['pro'];
        }
        if ($location) {
            return $location;
        } else {
            return false;
        }
    }
    /**
     * 是否存在某文本
     * @param {type}
     * @return:
     */

    public static function strexists($all, $find)
    {
        if (!$all) {
            return false;
        }
        return !(strpos($all, strval($find)) === false);
    }

    /**
     * 检查是否是邮箱
     * @param {type}
     * @return:
     */
    public static function checkEmail($value)
    {
        if (preg_match("/^[\w\.\-]+@\w+([\.\-]\w+)*\.\w+$/", $value) && strlen($value) <= 60) {
            return true;
        } else {
            return false;
        }
    }
    /**
     * 取中间文本
     * @param unknown $str
     * @param number $leftStr
     * @param number $rightStr
     */
    public static function getSubstr($str, $leftStr, $rightStr)
    {
        $left = strpos($str, $leftStr);
        $right = strpos($str, $rightStr, $left);
        if ($left < 0 or $right < $left) {
            return '';
        }
        return substr($str, $left + strlen($leftStr), $right - $left - strlen($leftStr));
    }
    /** 秒转换为天时分秒
     * @param $second
     * @return string
     */
    public static function time_last($second)
    {
        if ($second < 0) {
            return '已结束';
        }
        $day = floor($second / 86400);
        $second = $second - $day * 86400;

        $hour = floor($second / 3600);
        $second = $second - $hour * 3600;

        $minute = floor($second / 60);
        $second = $second - $minute * 60;

        return $day . '天' . $hour . '时' . $minute . '分' . $second . '秒';
    }
    /**
     * 获取数组随机下标
     *
     * @param [type] $proArr
     * @return void
     */
    public static function get_rand($proArr)
    {
        $result = "";
        $proSum = array_sum($proArr);
        foreach ($proArr as $key => $proCur) {
            $randNum = mt_rand(1, $proSum);
            if ($randNum <= $proCur) {
                $result = $key;
                break;
            }
            $proSum -= $proCur;
        }
        unset($proArr);
        return $result;
    }
    /**
     * 获取公网ip
     *
     * @return void
     */
    public static function getServerIp()
    {
        $url = 'http://members.3322.org/dyndns/getip';
        $url2 = 'https://www.bt.cn/Api/getIpAddress';
        if ($data = http::get($url2)) {
            return $data;
        } else {
            $data = http::get($url);
            return $data;
        }
    }
    /**
     * 钉钉通知
     * @param string 内容
     */
    public static function dingding($content, $token)
    {
        $webhook = "https://oapi.dingtalk.com/robot/send?access_token=" . $token;
        $data = array('msgtype' => 'text', 'text' => array('content' => $content));
        $data_string = json_encode($data);
        //return $data_string ;
        $rst = self::curl_json($webhook, $data_string);
        return $rst;
    }
    /**
     * 发送json请求 post
     */
    public static function curl_json($remote_server, $post_string)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $remote_server);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json;charset=utf-8'));
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        // 线下环境不用开启curl证书验证, 未调通情况可尝试添加该代码
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }
    /**
     * @param $second
     * @return string
     */
    public static  function  timelast($second)
    {
        if ($second < 0) {
            return '已结束';
        }
        $day = floor($second / 86400);
        $second = $second - $day * 86400;

        $hour = floor($second / 3600);
        $second = $second - $hour * 3600;


        $minute = floor($second / 60);
        $second = $second - $minute * 60;

        return $day . '天' . $hour . '时' . $minute . '分' . $second . '秒';
    }
}
